package com.linghui.videoplus.ipai.activity;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.linghui.videoplus.ipai.R;
import com.linghui.videoplus.ipai.VideoPlusApplication;
import com.linghui.videoplus.ipai.api.Preferences;
import com.linghui.videoplus.ipai.api.VideoPlusServerAPI;
import com.linghui.videoplus.ipai.api.WSError;
import com.linghui.videoplus.ipai.api.async.Callback;
import com.linghui.videoplus.ipai.api.async.IProgressListener;
import com.linghui.videoplus.ipai.api.async.ProgressCallable;
import com.linghui.videoplus.ipai.api.http.HttpPostUtil;
import com.linghui.videoplus.ipai.bean.AccountBean;
import com.linghui.videoplus.ipai.bean.SinaAccessBean;
import com.linghui.videoplus.ipai.bean.VideoBean;
import com.linghui.videoplus.ipai.utils.Constants;
import com.linghui.videoplus.ipai.utils.SinaTokenUtils;
import com.linghui.videoplus.ipai.utils.StringUtil;

public class AccountActivity extends BaseActivity implements OnTouchListener {

	private EditText emailEditText;
	private EditText userNameEditText;
	private EditText passwordEditText;
	private EditText rePasswordEditText;

	private EditText accountEditText;
	private EditText loginPasswordEditText;

	private Button registerButton;
	private ImageView sinaLoginImageView;

	private TextView loginTextView;

	private int FROM_CODE = REQUEST_CODE_DEFAULT;

	private String user_id = "";
	private String oauth_token_secret = "";
	private String oauth_token = "";

	private VideoBean video;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_account);

		FROM_CODE = getIntent().getIntExtra(FROM_CODE_KEY, REQUEST_CODE_DEFAULT);
		
		if(FROM_CODE==REQUEST_CODE_UPLOAD || FROM_CODE==REQUEST_CODE_SETTING){
			VideoPlusApplication.LAST_FROM_CODE=FROM_CODE;
			VideoPlusApplication.obj=getIntent().getSerializableExtra(SERIALIZABLE__KEY);
		}
		

		registerButton = (Button) findViewById(R.id.registerButton);
		registerButton.setOnTouchListener(this);

		sinaLoginImageView = (ImageView) findViewById(R.id.sinaLoginButton);
		sinaLoginImageView.setOnTouchListener(this);

		loginTextView = (TextView) findViewById(R.id.loginTextView);
		SpannableString msp = new SpannableString("登录");
		msp.setSpan(new UnderlineSpan(), 0, 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 
		loginTextView.setText(msp);
		loginTextView.setOnTouchListener(this);

		// registerTextView = (TextView) findViewById(R.id.registerTextView);
		// registerTextView.setText(Html.fromHtml("<a href=\"\">没有账号?点击这里快速注册</a>"));
		// registerTextView.setOnTouchListener(this);

		accountEditText = (EditText) findViewById(R.id.accountEditText);
		loginPasswordEditText = (EditText) findViewById(R.id.loginPasswordEditText);

		emailEditText = (EditText) findViewById(R.id.emailEditText);
		userNameEditText = (EditText) findViewById(R.id.userNameEditText);
		passwordEditText = (EditText) findViewById(R.id.passwordEditText);
		rePasswordEditText = (EditText) findViewById(R.id.rePasswordEditText);

		Uri uri = this.getIntent().getData();
		if (uri != null) {
			String oauth_verifier = uri.getQueryParameter("oauth_verifier");
			oauth_token = uri.getQueryParameter("oauth_token");
			uri = Uri.parse("http://example?"
					+ SinaTokenUtils.getAcsessToken(oauth_token,
							oauth_token_secret, oauth_verifier));
			oauth_token = uri.getQueryParameter("oauth_token");
			oauth_token_secret = uri.getQueryParameter("oauth_token_secret");
			user_id = uri.getQueryParameter("user_id");
			doSaveAuthKankan();
			super.showToast("新浪微博授权成功！");
			if(VideoPlusApplication.LAST_FROM_CODE==REQUEST_CODE_UPLOAD ){
				if(VideoPlusApplication.obj!=null){
					VideoBean bean=(VideoBean)VideoPlusApplication.obj;
					UploadActivity.launch(this, REQUEST_CODE_ACCOUNT, REQUEST_CODE_UPLOAD, bean);
				}
			}
			else if(VideoPlusApplication.LAST_FROM_CODE==REQUEST_CODE_SETTING ){
				SettingActivity.launch(this, REQUEST_CODE_ACCOUNT, REQUEST_CODE_SETTING);
			}
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		if(v==registerButton){
			if (event.getAction() == MotionEvent.ACTION_DOWN) {

			} else if (event.getAction() == MotionEvent.ACTION_UP) {
				final String email = emailEditText.getText().toString();
				final String nickName = userNameEditText.getText().toString();
				final String password = passwordEditText.getText().toString();
				final String rePassword = rePasswordEditText.getText().toString();
				doRegister(email, nickName, password, rePassword);
			}
			return true;
		}else if(v==loginTextView){
			if (event.getAction() == MotionEvent.ACTION_DOWN) {

			} else if (event.getAction() == MotionEvent.ACTION_UP) {
				final String name = accountEditText.getText().toString();
				final String pass = loginPasswordEditText.getText().toString();
				if(!VideoPlusApplication.checkNetWorkStatus(this)){
					showToast(this.getResources().getString(R.string.network_error_two));
				}
				doLogin(name, pass);
			}
			return true;
		}else if(v==sinaLoginImageView){
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				sinaLoginImageView.setBackgroundResource(R.drawable.sinaweibo_login_down);

			} else if (event.getAction() == MotionEvent.ACTION_UP) {
				sinaLoginImageView.setBackgroundResource(R.drawable.sinaweibo_up);
				if(!VideoPlusApplication.checkNetWorkStatus(this)){
					showToast(getResources().getString(R.string.network_error_two));
				}else{
					doSinaAuth2();
//				doSinaAuth();
				}
				
			}
			return true;
		}
		return true;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (FROM_CODE == REQUEST_CODE_UPLOAD) {
				this.setResult(RESULT_OK, getIntent());
				this.finish();
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 执行登录操作
	 * 
	 * @param name
	 * @param pass
	 */
	private void doLogin(final String name, final String pass) {
		if (checkLogin(name, pass)) {
			ProgressCallable<String> loginCallable = new ProgressCallable<String>() {
				@Override
				public String call(IProgressListener iProgressListener) {
					try {
						return new VideoPlusServerAPI().login(name, pass,
								Constants.KANKAN_ACCOUNT_LOGIN);
					} catch (WSError e) {
						e.printStackTrace();
					}
					return null;
				}
			};
			Callback<String> loginCallback = new Callback<String>() {
				@Override
				public void onCallback(String pCallbackValue) {
					if (pCallbackValue != null) {
						pCallbackValue = pCallbackValue.trim();
						int pCallbackValueInt = Integer
								.parseInt(pCallbackValue);
						switch (pCallbackValueInt) {
						case -1:// 密码为空,
							showToast("密码为空!");
							break;
						case -2:// 用户名为空
							showToast("用户名为空!");
							break;
						case -3:// 登录失败
							showToast("用户名或密码错误!");
							break;
						case -4:// 服务器繁忙
							showToast("服务器繁忙!");
							break;
						default:
							AccountBean accountBean=new AccountBean();
							accountBean.setUid(pCallbackValue);
							accountBean.setName(name);
							accountBean.setEmail("");
							accountBean.setPassword(pass);
							Preferences.saveKanKanAccessBean(AccountActivity.this, accountBean);
							showToast("登录成功!");
							if(FROM_CODE==REQUEST_CODE_UPLOAD ||FROM_CODE==REQUEST_CODE_SETTING){
								AccountActivity.this.setResult(RESULT_OK, getIntent());
								AccountActivity.this.finish();
							}
							
						}
					}
				}
			};
			super.doProgressDialogAsync(loginCallable, loginCallback);
		}

	}

	/**
	 * 执行注册操作
	 * 
	 * @param email
	 * @param nickName
	 * @param password
	 * @param rePassword
	 */
	private void doRegister(final String email, final String nickName,
			final String password, final String rePassword) {
		if (checkRegister(email, nickName, password, rePassword)) {
			ProgressCallable<String> registerCallable = new ProgressCallable<String>() {
				@Override
				public String call(IProgressListener iProgressListener) {
					String encoder = null;
					try {
						encoder = URLEncoder.encode(nickName, "UTF-8");
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
					Map<String, String> paraMap = new HashMap<String, String>();
					paraMap.put("username", encoder);
					paraMap.put("email", email);
					paraMap.put("password", password);
					paraMap.put("rePassword", rePassword);
					paraMap.put("regeditUrl", Constants.KANKAN_ACCOUNT_REGISTER);

					try {
						return new VideoPlusServerAPI().register(paraMap);
					} catch (WSError e) {
						e.printStackTrace();
					}
					return null;
				}
			};
			Callback<String> registerCallback = new Callback<String>() {
				@Override
				public void onCallback(String pCallbackValue) {

					if (!StringUtil.isEmpty(pCallbackValue)) {
						pCallbackValue = pCallbackValue.trim();
						int pCallbackValueInt = Integer
								.parseInt(pCallbackValue);
						switch (pCallbackValueInt) {
						case -1:
							showToast("用户名不合法!");
							break;
						case -2:
							showToast("用户名包含不允许注册的词语!");
							break;
						case -3:
							showToast("用户名已存在!");
							break;
						case -4:
							showToast("填写的Email格式有误!");
							break;
						case -5:
							showToast("填写的Email不允许注册!");
							break;
						case -6:
							showToast("填写的Email已经被注册!");
							break;
						case -7:
							showToast("注册失败 !");
							break;
						case -8:
							showToast("两次密码不一致!");
							break;
						case -9:
							showToast("密码空或包含非法字符!");
							break;
						case -10:
							showToast("密码太短!");
							break;
						case -11:
							showToast("服务器繁忙!");
							break;
						default:
							showToast("注册成功!");
						}
					}
				}
			};

			super.doProgressDialogAsync(registerCallable, registerCallback);
		}
	}

	private void doSinaAuth2() {
		new Thread() {
			public void run() {
				String tokenUrl = Constants.SINA_WEIBO_TOKEN_URL;
				String callBack=Constants.SINA_WEIBO_OAUTH_CALLBACK;
				String tempStr = SinaTokenUtils.getRequestToken(callBack);
				if (!tempStr.equals("error")) { // 如果获取失败
					Uri uri = Uri.parse("http://example?" + tempStr);
					String oauth_token = uri.getQueryParameter("oauth_token")
							.trim();
					oauth_token_secret = uri.getQueryParameter(
							"oauth_token_secret").trim();
					tokenUrl = tokenUrl + oauth_token;
					tokenUrl += "&oauth_callback="+callBack;
					Intent it = new Intent();
					it.putExtra("url", tokenUrl);
					it.putExtra(SERIALIZABLE__KEY, video);
					it.setClass(AccountActivity.this, SinaWebViewActivity.class);
					startActivityForResult(it, RESULT_OK);
					// startActivity(it);
				}
			}
		}.start();

	}

//	private void doSinaAuth() {
//		Weibo weibo = Weibo.getInstance();
//		weibo.setupConsumerConfig(Constants.SINA_WEIBO_APP_KEY,
//				Constants.SINA_WEIBO_APP_SECRET);
//		weibo.setRedirectUrl(Constants.SINA_WEIBO_OAUTH_CALLBACK);
//		weibo.authorize(this, new AuthDialogListener());
//	}

	/**
	 * 验证注册字段
	 * 
	 * @param email
	 * @param nickName
	 * @param password
	 * @param rePassword
	 * @return
	 */
	private boolean checkRegister(final String email, final String nickName,
			final String password, final String rePassword) {
		if (StringUtil.isEmpty(email)) {
			showToast("请输入注册邮件地址");
			return false;
		}

		if (!StringUtil.isEMailAddress(email)) {
			showToast("请输入正确的邮件地址");
			return false;
		}

		if (StringUtil.isEmpty(nickName)) {
			showToast("请输入昵称");
			return false;
		}

		if (StringUtil.isEmpty(password)) {
			showToast("请输入注册密码");
			return false;
		}

		if (StringUtil.isEmpty(rePassword)) {
			showToast("请输入确认密码");
			return false;
		}

		if (!StringUtil.compare(password, rePassword)) {
			showToast("输入密码不一致");
			return false;
		}
		return true;
	}

	/**
	 * 验证登录字段
	 * 
	 * @param name
	 * @param pass
	 * @return
	 */
	private boolean checkLogin(final String name, final String pass) {
		if (StringUtil.isEmpty(name)) {
			showToast("请输入用户名");
			return false;
		}
		if (StringUtil.isEmpty(pass)) {
			showToast("请输入密码");
			return false;
		}

		return true;
	}

	public static void launch(Activity mActivity, int fromCode, int toCode,Serializable obj) {
		Intent intent = new Intent(mActivity, AccountActivity.class);
		intent.putExtra(FROM_CODE_KEY, fromCode);
		intent.putExtra(TO_CODE_KEY, toCode);
		intent.putExtra(SERIALIZABLE__KEY, obj);
		mActivity.startActivity(intent);
		// mActivity.finish();
	}

	// 新浪微薄验证 AUTH2.0
//	class AuthDialogListener implements WeiboDialogListener {
//		@Override
//		public void onComplete(Bundle values) {
//			String token = values.getString("access_token");
//			String expires_in = values.getString("expires_in");
//			AccessToken accessToken = new AccessToken(token,
//					Constants.SINA_WEIBO_APP_SECRET);
//			accessToken.setExpiresIn(expires_in);
//			Weibo.getInstance().setAccessToken(accessToken);
//			Intent intent = new Intent();
//			intent.setClass(AccountActivity.this, SinaWebViewActivity.class);
//			startActivityForResult(intent, RESULT_OK);
//			// startActivity(intent);
//		}
//
//		@Override
//		public void onError(DialogError e) {
//			Toast.makeText(getApplicationContext(),
//					"Auth error : " + e.getMessage(), Toast.LENGTH_LONG).show();
//		}
//
//		@Override
//		public void onCancel() {
//			Toast.makeText(getApplicationContext(), "Auth cancel",
//					Toast.LENGTH_LONG).show();
//		}
//
//		@Override
//		public void onWeiboException(WeiboException e) {
//			Toast.makeText(getApplicationContext(),
//					"Auth exception : " + e.getMessage(), Toast.LENGTH_LONG)
//					.show();
//		}
//	};

	public void doSaveAuthKankan(){
		HttpPostUtil uapi;
		String result =null;
		try {
			uapi = new HttpPostUtil(Constants.KANKAN_ACCOUNT_AUTH);
			uapi.addTextParameter("type", "xinlang");
			uapi.addTextParameter("id", user_id);
			byte[] b = uapi.send();
			result = new String(b);
			Log.i("test", result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(result!=null &&  !result.equals("Register Failed")){
			SinaAccessBean sinaAccessBean = new SinaAccessBean();
			sinaAccessBean.setUserId(user_id);
			sinaAccessBean.setUserKey(oauth_token);
			sinaAccessBean.setUserSecret(oauth_token_secret);
			sinaAccessBean.setBandUserId(result);
			Preferences.saveSinaAccessBean(AccountActivity.this, sinaAccessBean);
		}
	}

}
